using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Library_management_system
{
    public partial class ReturnForm : Form
    {
        private string currentUsername;
        private int currentReaderId;

        public ReturnForm(string username)
        {
            InitializeComponent();
            currentUsername = username;
            currentReaderId = GetReaderId(username);
            LoadMyBorrows();
        }

        private int GetReaderId(string username)
        {
            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = "SELECT ReaderID FROM Users WHERE Username=@username";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", username);
                object result = cmd.ExecuteScalar();
                return (result != null && result != DBNull.Value) ? Convert.ToInt32(result) : -1;
            }
        }

        private void LoadMyBorrows()
        {
            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = @"SELECT br.RecordID, b.Title AS BookTitle, br.BorrowDate, br.DueDate 
                             FROM BorrowRecords br
                             JOIN Books b ON br.BookID = b.BookID
                             WHERE br.ReaderID = @ReaderID AND br.ReturnDate IS NULL";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@ReaderID", currentReaderId);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dgvBorrows.DataSource = dt;
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (dgvBorrows.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要归还的图书！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int recordId = Convert.ToInt32(dgvBorrows.SelectedRows[0].Cells["RecordID"].Value);
            DateTime dueDate = Convert.ToDateTime(dgvBorrows.SelectedRows[0].Cells["DueDate"].Value);

            if (MessageBox.Show("确定要归还该图书吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                using (SqlConnection conn = DatabaseConfig.GetConnection())
                {
                    conn.Open();
                    SqlTransaction transaction = conn.BeginTransaction();
                    try
                    {
                        // 1. 更新借阅记录
                        string sqlUpdateRecord = "UPDATE BorrowRecords SET ReturnDate=@ReturnDate WHERE RecordID=@RecordID";
                        SqlCommand cmdUpdateRecord = new SqlCommand(sqlUpdateRecord, conn, transaction);
                        cmdUpdateRecord.Parameters.AddWithValue("@ReturnDate", DateTime.Now);
                        cmdUpdateRecord.Parameters.AddWithValue("@RecordID", recordId);
                        cmdUpdateRecord.ExecuteNonQuery();

                        // 2. 更新图书可借数量
                        string sqlUpdateBook = "UPDATE Books SET AvailableCount = AvailableCount + 1 WHERE BookID = (SELECT BookID FROM BorrowRecords WHERE RecordID=@RecordID)";
                        SqlCommand cmdUpdateBook = new SqlCommand(sqlUpdateBook, conn, transaction);
                        cmdUpdateBook.Parameters.AddWithValue("@RecordID", recordId);
                        cmdUpdateBook.ExecuteNonQuery();

                        // 3. 检查是否超期，如果超期则生成罚款记录
                        if (DateTime.Now > dueDate)
                        {
                            decimal fineAmount = (decimal)(DateTime.Now - dueDate).TotalDays * 0.5m; // 假设每天罚款0.5元
                            string sqlInsertFine = "INSERT INTO Fines (RecordID, FineAmount, Paid) VALUES (@RecordID, @FineAmount, 0)";
                            SqlCommand cmdInsertFine = new SqlCommand(sqlInsertFine, conn, transaction);
                            cmdInsertFine.Parameters.AddWithValue("@RecordID", recordId);
                            cmdInsertFine.Parameters.AddWithValue("@FineAmount", fineAmount);
                            cmdInsertFine.ExecuteNonQuery();
                            MessageBox.Show($"还书成功！该书已超期，产生罚款 {fineAmount:C} 元。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("还书成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        MessageBox.Show("还书失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                LoadMyBorrows(); // 刷新借阅列表
            }
        }
    }
}